package com.example.springboot_selenium_demo.util;

import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.SessionId;
import org.openqa.selenium.remote.http.W3CHttpCommandCodec;
import org.openqa.selenium.remote.http.W3CHttpResponseCodec;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Collections;

import static org.openqa.selenium.remote.DriverCommand.NEW_SESSION;

public class ActiveHttpCommandExecutor extends HttpCommandExecutor {
	
	SessionId sessionId;
	public ActiveHttpCommandExecutor(SessionId sessionId, URL command_executor)
	{
		super(command_executor);
		this.sessionId=sessionId;
	}
	
		
	public Response execute(Command command) throws IOException {
		Response response = null;
		if (NEW_SESSION.equals(command.getName())) {
			response = new Response();
			response.setSessionId(sessionId.toString());
			response.setStatus(0);
			response.setValue(Collections.<String, String>emptyMap());

			try {
				Field commandCodec = null;
				commandCodec = this.getClass().getSuperclass().getDeclaredField("commandCodec");
				commandCodec.setAccessible(true);
				commandCodec.set(this, new W3CHttpCommandCodec());

				Field responseCodec = null;
				responseCodec = this.getClass().getSuperclass().getDeclaredField("responseCodec");
				responseCodec.setAccessible(true);
				responseCodec.set(this, new W3CHttpResponseCodec());
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}

		} else {
			response = super.execute(command);
		}
		return response;
	}
}
